package com.aiowang.springboot.single.activemq.utils;

import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.util.ByteSequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

/**
 *
 * @author aiowang
 * @date 2020/03/24
 */
public class SingleActiveMQUtils {

    public static final String CUSTOM_TOPIC_FACTORY = "customTopicFactory";
    public static final String CUSTOM_QUEUE_FACTORY = "customQueueFactory";

    private static JmsMessagingTemplate customActivemqTemplate;

    /**
     * 使用构造方式注入静态bean
     * @param customActivemqTemplate customActivemqTemplate
     */
    @Autowired
    public SingleActiveMQUtils(JmsMessagingTemplate customActivemqTemplate) {
        SingleActiveMQUtils.customActivemqTemplate = customActivemqTemplate;
    }
    /**
     * 获取纯文本信息。
     *
     * @param message 表示消息的Message对象。
     * @return 消息文字
     * @throws JMSException 错误
     * @throws ClassCastException 错误
     */
    public static String getTextMessage(Message message) throws JMSException, ClassCastException {
        if (message == null) {
            return null;
        }
        String ret = "";
        boolean isBytesMsg = message instanceof ActiveMQBytesMessage;
        if(isBytesMsg){
            ActiveMQBytesMessage abtmq =(ActiveMQBytesMessage) message;
            ByteSequence bts = abtmq.getContent();
            if (bts == null) {
                throw new ClassCastException("Message message connot cast to ActiveMQBytesMessage.");
            }
            ret = new String(bts.getData());
        }else{
            TextMessage text = (TextMessage) message;
            if (text == null) {
                throw new ClassCastException("Message message connot cast to TextMessage.");
            }
            ret = text.getText();
        }
        return ret;
    }


    /**
     * 发送主题消息
     * @param destination 发送主题
     * @param message 消息内容
     */
    public static void sendTopic(String destination, final String message){
        customActivemqTemplate.convertAndSend(new ActiveMQTopic(destination), message);
    }

    /**
     * 发送队列消息
     * @param destination 发送主题
     * @param message 消息内容
     */
    public static void sendQueue(String destination, final String message){
        customActivemqTemplate.convertAndSend(new ActiveMQQueue(destination), message);
    }
}
